#
# ShoeBox
#  A start product for Plone - ShoeBox
#
# ShoeBox.py
#  The Product
#
# Author: Christian Koller <admin@iecw.net>
#
# Released under GNU GPL v2 or later
#

from zLOG import LOG, INFO

from Products.Archetypes.public import *
from Products.ShoeBox.config import PROJECTNAME
from Products.CMFCore import CMFCorePermissions
from Products.CMFCore.WorkflowCore import ObjectMoved
from Products.validation import V_REQUIRED
from AccessControl import ClassSecurityInfo

from Products.ATContentTypes.content.schemata import ATContentTypeSchema
from Products.ATContentTypes.content.schemata import finalizeATCTSchema

from Products.ShoeBox.config import DIRECTIONS, PROJECTNAME

class ShoeBoxEntry(BaseContent):
    """ ShoeBox line entry """
    meta_type = 'ShoeBoxEntry'

    security  = ClassSecurityInfo()
#    _at_rename_after_creation = True # Don't do this, else duplicate titles will conflict

    schema = ATContentTypeSchema.copy() + Schema((
        StringField('account',
            searchable=0,
            required=1,
            #validators=('isAllowedUrl'),
            vocabulary = 'getAccounts',
            default_method='getDefaultAccount',
            widget=SelectionWidget(
                label='Account',
                label_msgid='account',
                i18n_domain='ShoeBox',
                format='flex',
            ),
        ),
        StringField('direction',
            searchable=0,
            required=1,
            vocabulary = DIRECTIONS,
            widget=SelectionWidget(
                label='Incoming/outgoing',
                label_msgid='direction',
                i18n_domain='ShoeBox',
                format='flex',
            ),
        ),
        # This is required, but it can be 0.00 which is the default
        FixedPointField('amount',
            searchable=0,
            required=0,
            widget=DecimalWidget(
                label='Amount',
                label_msgid='amount',
                description='The amount of money involved.',
                description_msgid='amount_description',
                size='10',
                i18n_domain='ShoeBox',
                dollars_and_cents=True,
            ),
        ),
        StringField('thirdparty',
            searchable=1,
            required=1,
            widget=StringWidget(
                label='Third party',
                label_msgid='thirdparty',
                description='The other party involved.',
                description_msgid='thirdparty_description',
                size='20',
                i18n_domain='ShoeBox',
            ),
        ),
        StringField('reference',
            searchable=1,
            required=0,
            widget=StringWidget(
                label='Reference',
                label_msgid='reference',
                description='The documentation.',
                description_msgid='reference_description',
                size='20',
                i18n_domain='ShoeBox',
            ),
        ),
        DateTimeField('date',
            searchable=0,
            required=1,
            widget=CalendarWidget(
                label='Date',
                label_msgid='date',
                description='The date of the transaction.',
                description_msgid='date_description',
                i18n_domain='ShoeBox',
                show_hm=False,
            ),
        ),

        ))
    
    finalizeATCTSchema(schema)
    ##
    ##  The Schema includes two variables, on for the Repository itself and one for a Path within the Repository
    ##

    def getAmount(self):
        """
        Returns amount as a float
        """
        return self.amount[0] + float(self.amount[1])/100.0

    ## Set the icon for the ShoeBox
    content_icon = 'shoebox.png'

    def getAccounts(self):
        """
        Returns a list of accounts available to this entry
        """
        accounts = self.getShoeBox().getAccounts()
        result = DisplayList()
        for account in accounts:
            result.add(account.getId(), account.Title())
        return result
    
    def getShoeBox(self):
        """
        Return the showbox which contains this entry
        """
        p = self.getFolderWhenPortalFactory()
        if p.meta_type == 'ShoeBoxAccount':
            p = p.getParentNode()
        return p
    
    def getIncomingOutgoingSelection(self):
        """
        Return a list which has incoming as false and outgoing as true
        """
        result = DisplayList()
        result.add(0, "Incoming")
        result.add(1, "Outgoing")
        return result

    def getDefaultAccount(self):
        p = self.getFolderWhenPortalFactory()
        if p.meta_type == 'ShoeBoxAccount':
            LOG("ShoeBoxEntry",INFO,'Setting parent to %s'%p.getId())
            return p.getId()
        else:
            return None

#    def manage_afterAdd(self, item, container):
#        LOG("ShoeBoxEntry",INFO,"manage_afterAdd")
#        super(ShoeBoxEntry, self).manage_afterAdd(item, container)
        
    def at_post_edit_script(self):
        LOG("ShoeBoxEntry",INFO,"at_post_edit_script")
        super(ShoeBoxEntry, self).at_post_edit_script()   
        self.moveToAccount()
        
    def at_post_create_script(self):
        LOG("ShoeBoxEntry",INFO,"at_post_create_script")
        super(ShoeBoxEntry, self).at_post_create_script()
        self.moveToAccount()

    def moveToAccount(self):
        """
        Move the entry to the correct account
        """
        LOG("ShoeBoxEntry",INFO,"Moving from %s to %s"%(self.getParentNode(), self.account))
        if self.getParentNode().getId() != self.account:
            dest = self.getShoeBox()[self.account]
            dest.manage_pasteObjects( self.getParentNode().manage_cutObjects(self.getId()) )
            new = dest[self.getId()]
#    def manage_beforeDelete(self, item, container):
#        LOG("ShoeBoxEntry",INFO,"manage_beforeDelete")
#        super(ShoeBoxEntry, self).manage_beforeDelete(item, container)
        
## Register the new type within Zope
registerType(ShoeBoxEntry,PROJECTNAME)
